<?php

class spListRadio extends spDiv
{
	public function __construct( $data=null )
	{
		parent::__construct( $data );
		parent::setClass( "spListRadio" );
		
		if ( isset($data["list"]) && count($data["list"]) ) 
			$this->addList( $data["list"] );		

		if ( isset($data["csv"]) && count($data["csv"]) ) 
			$this->addCSV( $data["csv"] );		
	}
	
	///////////////////////////////////////////////////////
	//
	//	add
	//	
	//		$item : array(
	//					"name" => "myname",
	//					"value" => "myvalue"
	//				);
	//
	///////////////////////////////////////////////////////
	
	public function add( $item )
	{
		$id	 		= isset($item["id"])?$item["id"]:"";
		$value 		= isset($item["value"])?$item["value"]:"";
		$name		= isset($item["name"])?$item["name"]."[]":"";
		$checked	= isset($item["checked"])?$item["checked"]:"false";
		
		$radio = new spInputRadio( array(
			"name_id"	=> $value,
			"name" 		=> $name,
			"value" 	=> $value,
			"checked"	=> $checked
		));
		parent::addChild( $radio );
		
		$label =  new spLabel(array(
			"content" => $value
		));		
		parent::addChild( $label );
		
		if ( $id!="" )
		{
			$radio->setId( $id );
			$label->setFor( $id );
		}
		
		parent::addChild( new spBreak );
	}
	
	public function addList( $list )
	{
		$data = parent::getData();
		$name = $data["name"];
		
		foreach ( $list as $i )
		{
			$this->add(array(
				"name" => $name,
				"value" => $i["value"]
			));
		}
	}
	
	public function addCSV( $csv )
	{
		$data = parent::getData();
		$name = $data["name"];
	
		$ar = explode( ",", $csv );
		foreach ( $ar as $a )
		{
			$this->add(array(
				"name"=>$name,
				"value"=>$a,
				"content"=>$a
			));
			
			parent::addChild( new spBreak );
		}		
	}
	
	public function selectItem( $name_id )
	{
		$checkbox = parent::find($name_id);
		if ( $checkbox==false )
		{
			echo "ERROR: spListRadio.php -> selectItem ".$name_id;
			return false;
		}
		
		$checkbox->addAttr( "checked", "checked" );	
		return $checkbox;
	}	
	
	public function setElementDataString( $s )
	{
		parent::setElementDataString( $s );
		
		$name_id = current( $s );
		$this->selectItem( $name_id );
	}
	
	public function updateFromRequest()
	{
		parent::updateFromRequest();
		
		// convinence variables
		$data = parent::getData();
		$r = $_REQUEST;			

		if ( !isset($data["name"]) )
			return true;
		
		if ( !isset($r[$data["name"]]) )
			return true;
			
		// should only be one item in the array
		$ar = $r[$data["name"]];
			
		$this->setElementDataString( $ar );
	}	
}

?>